import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document, Schema as MongooseSchema } from 'mongoose';
import * as bcrypt from 'bcrypt';
import { ApiProperty } from '@nestjs/swagger';

export type UserDocument = User & Document;

// 扩展接口以包含模式方法
export interface User {
  comparePassword(candidatePassword: string): Promise<boolean>;
  toObject(): any;
}

@Schema({ timestamps: true })
export class User {
  @ApiProperty({ description: '用户名，唯一标识' })
  @Prop({ required: true, unique: true })
  username: string;

  @ApiProperty({ description: '密码，已加密存储' })
  @Prop({ required: true })
  password: string;

  @ApiProperty({ description: '真实姓名' })
  @Prop()
  realName: string;

  @ApiProperty({ description: '电子邮箱' })
  @Prop()
  email: string;

  @ApiProperty({ description: '手机号码' })
  @Prop()
  phone: string;

  @ApiProperty({ description: '用户状态：0-禁用，1-启用', default: 1 })
  @Prop({ default: 1 }) // 0: 禁用, 1: 启用
  status: number;

  @ApiProperty({ description: '上次登录时间' })
  @Prop()
  lastLoginTime: Date;

  @ApiProperty({ description: '所属组织ID' })
  @Prop({ type: MongooseSchema.Types.ObjectId, ref: 'Organization' })
  orgId: MongooseSchema.Types.ObjectId;

  @ApiProperty({ description: '角色ID列表', type: Array })
  @Prop({ type: [{ type: MongooseSchema.Types.ObjectId, ref: 'Role' }] })
  roleIds: MongooseSchema.Types.ObjectId[];

  @Prop()
  avatar: string;

  @Prop()
  fullName: string;

  @Prop({ default: false })
  isAdmin: boolean;

  @Prop()
  userId: string;
}

export const UserSchema = SchemaFactory.createForClass(User);

// 密码加密中间件
UserSchema.pre<UserDocument>('save', async function(next) {
  if (!this.isModified('password')) {
    return next();
  }

  try {
    const salt = await bcrypt.genSalt(10);
    this.password = await bcrypt.hash(this.password, salt);
    next();
  } catch (error) {
    next(error as Error);
  }
});

// 验证密码方法
UserSchema.methods.comparePassword = async function(candidatePassword: string): Promise<boolean> {
  return bcrypt.compare(candidatePassword, this.password);
}; 